import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  // isLoading: false,       // 路由过渡状态

  openId: '',             // openid
  appUser: {
    id: -1,
    agencyCode: '',
    headIcon: '/front/static/images/user_green.png',
    nickName: '未获取',
    consumeCount: -1,
    consumeAmount: -1
  },                      // 应用用户信息
  userInfo: {},           // 微信用户信息
  onceCard: {},           // 次卡属性
  monthCard: {},          // 月卡属性
  workList: [],           // 工种列表
  agencyList: [],         // 代理商列表
  userAllCardInfo: [],    // 用户所有卡的信息
  userCardInfo: {},       // 用户某个卡的信息！！！
  userMonthCardInfo: [],  // 用户的即将到期的月卡信息
  examSets: {},           // 考试设置
  sysconfig: {},           // 系统关于题目总数，抽题比例的设置
  dicTypes: [],           // 字典类型值数组
  workTypeKV: [],         // 工种键值对（工种代码==工种名称）
  workCardKV: [],         // 卡类型键值对（卡代码==卡名称）
  questionKV: [],          // 题型键值对（题型代码==题型名称）
  questionPaper: [],      // 根据工种抽取的题目集合

  // 保存记录条数和时间
  MAX_HISTORY_COUNT: 10,
  MAX_HISTORY_DAYS: -7,

  // 预置代码
  EXAM_SET: 'normal',       // 考试设置
  RESULT_CODE: 0,
  CODE_ZERO: 0,
  USER_CARD_ENABLE_STATUS: 10001001, // 用户启用状态代码

  thisstart: '',
  jssdk: '/vx/api/jssdk/signature',                             // jssdk授权地址
  vxApiPay: '/vx/api/pay',                                      // 支付
  vxPersonalBind: '/vx/personal/bind',                          // 执行用户绑定--------------------------------------
  vxPersonalIsBind: '/vx/personal/isBind',                      // 检查用户是否绑定---------------------------------

  vxUserCardInfo: '/vx/usercard/info/',                         // 根据用户卡ID获取用户卡信息
  vxUserCardMonthCardInfo: '/vx/usercard/monthCardInfo',        // 根据已授权的微信页面获取用户月卡信息
  vxExamsetGetValue: '/vx/examset/getValue',                    // 根据设置代码获取考试设置(默认：normal)
  vxQuestionsGenTypeSubRdmExamPaper: '/vx/questions/genTypeSubRdmExamPaper', // 根据工种参数分段随机抽题
  vxSysconfigGetValue: '/vx/sysconfig/getValue',                // 根据键获取值(strategy_rdm_10031001(选择),strategy_rdm_10031002(判断))
  vxDicTypes: '/vx/dic/types/',                                 // 根据字典类型号码获取字典值
  vxCardInfo: '/vx/card/info/',                                 // 获取基本卡的信息，编号分别1，2就两种

  vxPersonalWeiChatUserInfo: '/vx/personal/weiChatUserInfo',    // 系统自动获取已授权的微信页面获取微信用户信息。
  vxAgencyList: '/vx/agency/list',                              // 获取代理商列表
  vxQuestionTypesList: '/vx/questions/types/list',              // 工种类型列表
  vxUsercardAllCardInfo: '/vx/usercard/allCardInfo',            // 根据已授权的微信页面获取用户所有可用卡信息

  vxUsercardBuyMonthCard: '/vx/usercard/buyMonthCard',          // 系统自动获取已授权的微信页面购买月卡或续期。
  vxUsercardBuySingleCard: '/vx/usercard/buySingleCard',        // 系统自动获取已授权的微信页面并根据提交卡片张数购买次卡。
  vxUsercardConsumeCard: '/vx/usercard/consumeCard',            // 执行消费购买的卡

  thisend: ''

}

const mutations = {
  // 更新openid
  updateOpenId (state, payload) {
    state.openId = payload.openId
  },

  /// //////////////////////////////////////////
  // 01:获取用户信息
  vxPersonalWeiChatUserInfo () {
    Vue.http({
      url: this.state.vxPersonalWeiChatUserInfo,
      method: 'post',
      params: {openId: this.state.openId}
    }).then((res) => {
      // console.log('getvxPersonalWeiChatUserInfo Start')
      if (res.data.code === 0) {
        this.state.appUser = res.data.appUser
        this.state.userInfo = res.data.userInfo
        console.log('getvxPersonalWeiChatUserInfo Success')
        console.log(res)
      } else {
        console.log('getvxPersonalWeiChatUserInfo Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('getvxPersonalWeiChatUserInfo Error')
      console.log(error.response)
    })
  },
  // 02:获取代理商列表
  vxAgencyList () {
    Vue.http.get(this.state.vxAgencyList).then((res) => {
      // console.log('vxAgencyList Start')
      if (res.data.code === 0) {
        this.state.agencyList = res.data.agency
        console.log('vxAgencyList Success')
        console.log(res)
      } else {
        console.log('vxAgencyList Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('vxAgencyList Error')
      console.log(error.response)
    })
  },
  // 03:获取工种信息
  vxQuestionTypesList () {
    Vue.http.get(this.state.vxQuestionTypesList).then((res) => {
      // console.log('vxQuestionTypesList Start')
      if (res.data.code === 0) {
        this.state.workList = res.data.data
        console.log('vxQuestionTypesList Success')
        console.log(res)
      } else {
        console.log('vxQuestionTypesList Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('vxQuestionTypesList Error')
      console.log(error.response)
    })
  },

  // 04:获取用户的所有的可用的卡
  vxUsercardAllCardInfo () {
    Vue.http.get(this.state.vxUsercardAllCardInfo).then((res) => {
      // console.log('vxUsercardAllCardInfo Start')
      if (res.data.code === 0) {
        this.state.userAllCardInfo = res.data.userCardList
        console.log('vxUsercardAllCardInfo Success')
        console.log(res)
      } else {
        this.state.userAllCardInfo = res.data
        console.log('vxUsercardAllCardInfo Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('vxUsercardAllCardInfo Error')
      console.log(error.response)
    })
  },

  // 05: 获取数据字典中键值对
  // 工种键值对
  // 卡的种类
  // 题目类型键值对
  vxDicTypesValueKey (state, payload) {
    var myDictionaryType = []
    Vue.http.get(this.state.vxDicTypes + payload.tpyeId).then((res) => {
      // console.log('vxDicTypesAndWorkType Start')
      if (res.data.code === 0) {
        // console.log('vxDicTypesAndWorkType Success')
        for (var i = 0; i < res.data.types.length; i++) {
          myDictionaryType.unshift({key: res.data.types[i].codeId, value: res.data.types[i].codeDesc})
        }
        switch (payload.stateName) {
          case 'workTypeKV':
            console.log('vxDicTypesAndWorkType workTypeKV')
            this.state.workTypeKV = myDictionaryType
            break
          case 'workCardKV':
            console.log('vxDicTypesAndWorkType workCardKV')
            this.state.workCardKV = myDictionaryType
            break
          case 'questionKV':
            console.log('vxDicTypesAndWorkType questionKV')
            this.state.questionKV = myDictionaryType
        }
        console.log(myDictionaryType)
      } else {
        console.log('vxDicTypesAndWorkType 其他返回代码')
        console.log(res)
      }
    }).catch((error) => {
      console.log('vxDicTypesAndWorkType Error')
      console.log(error.response)
    })
  },

  // 06: 获得月卡和次卡的详细信息
  vxCardInfo (state) {
    Vue.http.get(this.state.vxCardInfo + '1').then((res) => {
      // console.log('vxCardInfo Start')
      if (res.data.code === 0) {
        this.state.onceCard = res.data.card
        console.log('vxCardInfo Success')
        console.log(res)
      } else {
        console.log('vxCardInfo Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('vxCardInfo Error')
      console.log(error.response)
    })
    Vue.http.get(this.state.vxCardInfo + '2').then((res) => {
      // console.log('vxCardInfo Start')
      if (res.data.code === 0) {
        this.state.monthCard = res.data.card
        console.log('vxCardInfo Success')
        console.log(res)
      } else {
        console.log('vxCardInfo Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('vxCardInfo Error')
      console.log(error.response)
    })
  },

  // 07: 根据设置代码获取考试设置(默认：normal)
  vxExamsetGetValue (state, payload) {
    // console.log('vxExamsetGetValue is start')
    Vue.http({
      url: this.state.vxExamsetGetValue,
      method: 'get',
      params: {code: payload.code}
    }).then((res) => {
      console.log('vxExamsetGetValue is success')
      console.log(res)
      if (res.data.code === 0) {
        this.state.examSets = res.data.examSet
        console.log(res.data.examSet)
      }
    }).catch((error) => {
      console.log('vxExamsetGetValue is fail')
      console.log(error.response)
    })
  },
    // 08: 获取系统设置：
    // exam_paper_count ：试卷题目数
    // strategy_rdm_10031001：选择题百分百
    // strategy_rdm_10031002：判断题百分百
    // vxSysconfigGetValue
  vxSysconfigGetValue (state) {
    // console.log('vxSysconfigGetValue start')
    var result = {}
    Vue.http.get(this.state.vxSysconfigGetValue, {params: {key: 'exam_paper_count'}}).then((res) => {
      console.log('exam_paper_count')
      console.log(res)
      result.ExerciseQuestionAmount = res.data.key
      // localStorage.setItem('ExerciseQuestionAmount', res.data.key)
    })
    Vue.http.get(this.state.vxSysconfigGetValue, {params: {key: 'strategy_rdm_10031001'}}).then((res) => {
      console.log('strategy_rdm_10031001')
      console.log(res)
      result.ChoiceCount = res.data.key
      // localStorage.setItem('ChoiceCount', res.data.key)
    })
    Vue.http.get(this.state.vxSysconfigGetValue, {params: {key: 'strategy_rdm_10031002'}}).then((res) => {
      console.log('strategy_rdm_10031002')
      console.log(res)
      result.JudgmentCount = res.data.key
      // localStorage.setItem('JudgmentCount', res.data.key)
    })
    // Vue.http.get(this.state.vxSysconfigGetValue, {params: {key: 'strategy_rdm_10031002'}}).then((res) => {
    //   console.log(res)
    //   result.JudgmentCount = res.data.key
    //   localStorage.setItem('JudgmentCount', res.data.key)
    // })
    console.log(result)
    this.state.sysconfig = result
  }
}

const actions = {
  // // 首页Home编排

  async homeInit ({dispatch}) {
    await dispatch('getUserInfo')
    await dispatch('getCardInfo')
    await dispatch('getWorkList')
    await dispatch('getWorkType')
    await dispatch('getUserAllCardInfo')
  },

  // // 用户中心userCenter编排

  async userCenterInit ({dispatch}) {
    await dispatch('getUserInfo')
    await dispatch('getAgencyList')
    await dispatch('getWorkList')
    await dispatch('getUserAllCardInfo')
  },

  // // 购买卡 cardPayment

  async cardPaymentInit ({dispatch}) {
    await dispatch('getCardInfo')
    await dispatch('getWorkType')
    await dispatch('getCardType')
    await dispatch('getUserInfo')
    await dispatch('getAgencyList')
  },

  // selectUserCard

  async selectUserCardInit ({dispatch}) {
    await dispatch('getUserAllCardInfo')
    await dispatch('getWorkType')
  },

  // GetExercise

  async getExerciseInit ({dispatch}) {
    await dispatch('getSysconfig')
    await dispatch('getExamSet')
    await dispatch('getUserInfo')
    await dispatch('getUserAllCardInfo')
    await dispatch('getQuestionType')
  },

  // TheExerciseFrame

  async theExerciseFrameInit ({dispatch}) {
    await dispatch('getQuestionType')
    await dispatch('getSysconfig')
    await dispatch('getExamSet')
  },

  // reviewExercises
  async reviewExercises ({dispatch}) {
    await dispatch('getSysconfig')
  },

  // 01: 获取用户信息
  getUserInfo (_this) {
    _this.commit('vxPersonalWeiChatUserInfo')
  },
  // 02: 获取代理商列表
  getAgencyList (_this) {
    _this.commit('vxAgencyList')
  },
  // 03: 获取工种信息
  getWorkList (_this) {
    if (this.state.workList.length === 0) {
      _this.commit('vxQuestionTypesList')
    }
  },
  // 04: 获取用户的所有可用卡的信息
  getUserAllCardInfo (_this) {
    _this.commit('vxUsercardAllCardInfo')
  },
  // 05: 根据编号获得此数据字典的键值对-工种列表
  getWorkType (_this, payload) {
    if (state.workTypeKV.length === 0) {
      _this.commit('vxDicTypesValueKey', {tpyeId: '1006', stateName: 'workTypeKV'})
    }
  },
  // 05: 根据编号获得此数据字典的键值对-卡的类型列表
  getCardType (_this, payload) {
    if (state.workCardKV.length === 0) {
      _this.commit('vxDicTypesValueKey', {tpyeId: '1001', stateName: 'workCardKV'})
    }
  },
  // 05: 根据编号获得此数据字典的键值对-题目类型列表
  getQuestionType (_this, payload) {
    if (state.questionKV.length === 0) {
      _this.commit('vxDicTypesValueKey', {tpyeId: '1003', stateName: 'questionKV'})
    }
  },
  // 06: 获得月卡和次卡的信息
  getCardInfo (_this) {
    if (
      JSON.stringify(this.state.onceCard) === '{}' ||
      JSON.stringify(this.state.monthCard) === '{}'
      ) {
      _this.commit('vxCardInfo')
    }
  },
  // 07: 根据设置代码获取考试设置(默认：normal)
  getExamSet (_this, payload) {
    if (JSON.stringify(this.state.examSets) === '{}') {
      _this.commit('vxExamsetGetValue', {code: 'normal'})
    }
  },
  // 08: 获取系统参数
  getSysconfig (_this) {
    if (JSON.stringify(this.state.sysconfig) === '{}') {
      _this.commit('vxSysconfigGetValue')
    }
  }
}

const getters = {
  // 检查用户是否具体此工种的卡
  hasWork: (state) => (id) => {
    if (JSON.stringify(state.userAllCardInfo).indexOf(id) === -1) {
      return false
    } else {
      return true
    }
  },
  // 获取工种（类型代码==工种名字）键值对（Home）
  workTypeVK: (state) => {
    return state.workTypeKV
  },
  // 卡类型（类型代码==卡名字）键值对
  workCardVK: (state) => {
    var cardArray = state.workCardKV.sort()
    return cardArray
  },
  questionVK: (state) => {
    return state.questionKV
  },
  // 获取用户的信息（public）
  appUserInfo: (state) => {
    return state.appUser
  },
  // 代理商列表
  agencyList: (state) => {
    return state.agencyList
  },
  // 获取用户拥有的卡的键值对对象（usercenter）
  myCardVK: (state) => {
    var allCard = state.userAllCardInfo
    var vk = []
    for (let i = 0; i < allCard.length; i++) {
      // vk.push({key: allCard[i].cardId, value: allCard[i].cardNo})
      vk.push({key: allCard[i].cardNo, value: allCard[i].cardNo})
    }
    console.log(vk)
    return vk
  },

  // 获取全部可用的卡的信息（usercenter）
  allCardInfo: (state) => {
    return state.userAllCardInfo
  },

  // 获取月卡信息
  onceCardInfo: (state) => {
    return state.onceCard
  },
  // 获取次卡信息
  monthCardInfo: (state) => {
    return state.monthCard
  },
  // 根据题行名称（选择题，判断题）获取题型的代码
  getQuestionCode: (state) => (name) => {
    var questKV = state.questionKV
    for (var i = 0; i < questKV.length; i++) {
      if (questKV[i].value === name) {
        return questKV[i].key
      }
    }
  }
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})
